<template>
  <div>
    <van-nav-bar title="我的收货地址"
                 left-text="返回"
                 left-arrow
                 @click-left="onClickLeft" />

    <van-address-list v-model="chosenAddressId"
                      :list="list"
                      default-tag-text="默认"
                      @add="onAdd"
                      @edit="onEdit"
                      @select="onSelect" />
  </div>
</template>
<script>
export default {
  created() {
    this.AddressList()
  },
  data() {
    return {
      chosenAddressId: 0,
      list: [],
      LoginUser: this.$cookies.get('LoginUser'),
    }
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    onAdd() {
      this.$router.push({
        path: '/user/address/add',
      })
    },
    onEdit(item) {
      this.$router.push({
        path: '/user/address/edit',
        // 跳转时所携带的数据
      })
    },
    // 修改默认地址
    async onSelect(item) {
      // 封装请求的数据
      let data = {
        id: item.id,
        userid: this.LoginUser.id,
        consignee: item.name,
        mobile: item.tel,
      }
      this.$cookies.set('AddressOrder', data)
      console.log(data)
      // 将data传给后台的select并返回select的数据
      let result = await this.$api.select(data)
      if (result.code === 0) {
        this.$notify({
          type: 'danger',
          message: result.msg,
          duration: 1500,
        })
        return false
      }
      this.AddressList()
    },
    async AddressList() {
      // 请求后台获取某个用户的收货地址 将属性传给后台
      let result = await this.$api.AddressIndex({ userid: this.LoginUser.id })

      // 获取到data数据并且赋值
      let data = result.data

      // 空数组
      let list = []

      // 当没数据提示
      if (data.length <= 0) {
        this.$notify({
          type: 'danger',
          message: '暂无收货地址',
          duration: 1500,
        })
        return false
      }
      // 把data里循环重组一个新的数据
      for (var item of data) {
        // 查找默认地址
        if (item.status == 1) {
          this.chosenAddressId = item.id
        }

        // 重组数据
        let address = {
          id: item.id,
          name: item.consignee,
          tel: item.mobile,
          isDefault: item.status == 1 ? true : false,
        }

        // 详细地址
        let info = ''

        if (item.provinces) {
          info += `${item.provinces.name}-`
        }

        if (item.citys) {
          info += `${item.citys.name}-`
        }

        if (item.districts) {
          info += `${item.districts.name} `
        }

        if (item.address) {
          info += `${item.address}`
        }

        // 追加address属性到address数组并且值为info
        address.address = info

        // 追加到数组到List
        list.push(address)
      }

      // 赋值
      this.list = list
    },
  },
}
</script>